import { Context, ContextConfig } from "./contest";
import { EnvironmentContext } from "./environment";

export class EneityContext extends Context {
    /** 动作结果 */
    private actionResult: {
        old: any;
        new: any;
    } = {
        old: null,
        new: null
    };
    /** 动作结果暂存 */
    private actionResultTemp: {
        old: any;
        new: any;
    } = {
        old: null,
        new: null
    };

    update(config: { result: any } & ContextConfig) {
        this.actionResult.old = this.actionResult.new;
        this.actionResult.new = config.result;
        super.update(config);
    }
    updateTemp(config: { result: any } & ContextConfig) {
        this.actionResultTemp.old = this.actionResult.old;
        this.actionResultTemp.new = this.actionResult.new;
        super.update(config);
    }
    updateTempToReal() {
        this.actionResult.old = this.actionResultTemp.old;
        this.actionResult.new = this.actionResultTemp.new;
    }
    getData() {
        const superDate = super.getData();
        return {
            ...superDate,
            actionResult: this.actionResult
        };
    }
    reset() {
        super.reset();
        this.actionResult = {
            old: null,
            new: null
        };
    }
}

export interface EntityConfig {
    /** 名称 */
    name: string;
    /** 类型 */
    type: string;
    /** 上下文 */
    context?: EneityContext;
}

export abstract class Entity {
    public name: string;
    public type: string;
    public context: EneityContext;

    constructor(config: EntityConfig) {
        this.name = config.name;
        this.type = config.type;
        this.context = config.context ?? new EneityContext({ frame: 0 });
    }

    abstract action(
        entitys: Record<string, Entity>,
        context: EnvironmentContext
    ): Promise<any> | any;
}
